package manager;

import interfaz.ManagerSAIf;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import domain.Articulo;
import domain.SolicitudArticulo;
import dto.SolicitudArticuloDTO;
import exceptions.ExceptionSolicitudArticulo;


@Stateless
public class ManagerSA   implements ManagerSAIf{
	private static Logger logger = Logger.getLogger(ManagerSA.class);
	@PersistenceContext(unitName="tpoai")
    EntityManager em;

	public ManagerSA() throws RemoteException {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<SolicitudArticuloDTO> getSolicitudesArticulo() throws ExceptionSolicitudArticulo,	RemoteException {
		@SuppressWarnings("rawtypes")
		Iterator q = em.createQuery("select s from SolicitudArticulo s").getResultList().iterator();
		
		List<SolicitudArticuloDTO> arts=new ArrayList<SolicitudArticuloDTO>();
		
		  while(q.hasNext())
		  {
			  SolicitudArticulo c = (SolicitudArticulo)q.next();
			  arts.add(c.getVista());
		  }
		  return arts;
	}

	@Override
	public Integer save(SolicitudArticuloDTO sa)throws ExceptionSolicitudArticulo, RemoteException {
		SolicitudArticulo s = new SolicitudArticulo();
		s.setEstado(sa.getEstado());
		s.setArticulo(em.find(Articulo.class, sa.getArticulo().getId()));
		s.setCantidadPedida(sa.getCantidadPedida());
		s.setCantidadRecibida(sa.getCantidadRecibida());
		s.setIdModulo(sa.getIdModulo());
		
		//LLegan todos los valores bien, pero no persiste
		
		em.persist(s);
		em.flush();
		
		System.out.println("PERSISTIO" +s.getId());
		return s.getId();
	}

	@Override
	public SolicitudArticuloDTO getSolicitudById(Integer id)throws ExceptionSolicitudArticulo, RemoteException {
		@SuppressWarnings({ "unchecked" })
		List<SolicitudArticulo> solicitudes = 	(List<SolicitudArticulo>)em.createQuery("select s from SolicitudArticulo s where s.id = :id").setParameter("id", id).getResultList();
		if (solicitudes!=null && solicitudes.size()>0) {
			return solicitudes.get(0).getVista();
		}
		return null;
	}

}
